﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FFMpegSharp;

namespace winform_ffmpeg_video_convert_audio {
  public partial class frmMain : Form {
    public frmMain() {
      InitializeComponent();
    }

    private void btnFileSelect_Click(object sender, EventArgs e) {
      openFileDialog1.Title = "请选择视频文件";
      openFileDialog1.Filter = "所有文件(*.*)|*.*";
      if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        string filePath = openFileDialog1.FileName;
        textFilePath.Text = filePath;
      }
    }

    private void btnLogClear_Click(object sender, EventArgs e) {
      textLog.Text = "";
    }

    private void btnConvertFile_Click(object sender, EventArgs e) {
      var outputPath = VideoPathUtils.getOutputPath(textFilePath.Text);
      //LogUtils.log(outputPath, textLog);
      FFmpegUtils.ExtractAudio(textFilePath.Text, outputPath,textLog);
    }

    private void btnGetVideoInfo_Click(object sender, EventArgs e) {
      var videoInfo = new VideoInfo(textFilePath.Text);
      LogUtils.WriteLine(videoInfo.ToString(), textLog);
    }

    

    private void button3_Click(object sender, EventArgs e) {
      
      if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        string filePath = folderBrowserDialog1.SelectedPath;
        textFolderPath.Text = filePath;
      }
    }

    private void btnFolderConvert_Click(object sender, EventArgs e) {

      //AVI、mov、rmvb、rm、FLV、mp4、3GP
      //FileInfo[] files =directoryInfo.GetFiles("*.avi,*.mov,*.rmvb,*.rm,*.FLV,*.mp4,*.3GP");
      //测试失败


      DirectoryInfo directoryInfo = new DirectoryInfo(textFolderPath.Text);
      var listFile = new List<FileInfo>();
      getVideoFileWithRecursive(directoryInfo, listFile);

      var length = listFile.Count;
      LogUtils.WriteLine(String.Format("size:{0}", length), textLog);
      for (int i = 0; i < length; i++) {
        FileInfo fi = listFile[i];
        var outputPath = VideoPathUtils.getOutputPath(fi.FullName);
        //LogUtils.log(outputPath, textLog);
        FFmpegUtils.ExtractAudio(fi.FullName, outputPath, textLog);
        LogUtils.WriteLine(String.Format("{0}/{1}", (i + 1) , length),textLog);
      }
    }

    private void getVideoFileWithRecursive(DirectoryInfo directoryInfo, List<FileInfo> listFile) {
      //测试成功,支持大小写
      FileInfo[] fis = new string[] { "*.avi", "*.mov", "*.rmvb", "*.rm", "*.flv", "*.mp4", "*.3gp" }
        .SelectMany(i => directoryInfo.GetFiles(i, SearchOption.AllDirectories))
        .Distinct().ToArray();

      foreach (var fi in fis) {
        listFile.Add(fi);
      }

      DirectoryInfo[] ds = directoryInfo.GetDirectories();
      foreach (var d in ds) {
        getVideoFileWithRecursive(d, listFile);
      }
    }
  }
}
